package br.edu.infnet.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import br.edu.infnet.hibernate.util.HibernateUtil;
import br.edu.infnet.modelo.Modulo;



public class ModuloDAO {

	private Session session;

	public void incluir(Modulo m) {
		try {
			session = HibernateUtil.getSession();
			session.beginTransaction();
			session.save(m);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
	}

	public void alterar(Modulo m) {
		try {
			session = HibernateUtil.getSession();
			session.beginTransaction();
			session.save(m);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
	}
	
	public void excluir(Modulo m) {
		try {
			session = HibernateUtil.getSession();
			session.beginTransaction();
			session.delete(m);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
	}

	public Modulo consultar(Integer codigo) {
		Modulo retorno = new Modulo();
		try {
			session = HibernateUtil.getSession();
			session.beginTransaction();
			retorno = (Modulo) session.get(Modulo.class, codigo);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return retorno;
	}

	@SuppressWarnings("unchecked")
	public List<Modulo> listar() {
		List<Modulo> lista = new ArrayList<Modulo>();
		try {
			session = HibernateUtil.getSession();
			session.beginTransaction();
			lista = (List<Modulo>) session.createCriteria(Modulo.class).list();
			session.getTransaction().commit();
		} catch (Exception e) {			
			session.getTransaction().rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return lista;
	}

	@SuppressWarnings("unchecked")
	public List<Modulo> listar(Modulo m) {
		Criteria c = session.createCriteria(Modulo.class);
		if (m.getNome().length() > 0) {
			c.add(Restrictions.like("nome", m.getNome() + "%"));
		}
		c.addOrder(Order.asc("nome"));
		return (List<Modulo>) c.list();
	}

}
